import React, { Component } from 'react';
import {
  Button, Card, Col, Form, Icon,
  Input, Modal, Row, Select, Switch,
} from 'antd';
import { connect } from 'dva';
import tools from '../../utils';
import md5 from '../../utils/md5';
import { pageSize, modalWidth } from '../../../config';
import PageHeaderLayout from '@/components/PageHeaderWrapper';
import StandardTable from '../../components/StandardTable';
import SearchForm from '../../utils/searchForm';

const pageTitle = '用户管理';
const dlgTitle = '用户';
let reqApi = '';
let changeValues = {};
const formItemLayout = {
  labelCol: { md: 3, xs: 7 },
  wrapperCol: { md: 21, xs: 17 },
};
const formItemLayout2 = {
  labelCol: { md: 6, xs: 7 },
  wrapperCol: { md: 18, xs: 17 },
};

const fields = [
  {
    title: '用户名',
    title2: '用 户 名',
    dataIndex: 'userName',
    type: 'text',
  },
  {
    title: '姓名',
    title2: '姓　　名',
    dataIndex: 'name',
  },
  {
    title: '手机号码',
    dataIndex: 'phone',
    render: text => tools.funcPhoneSpace(text),
  },
  {
    title: '用户状态',
    dataIndex: 'status',
    type: 'select',
    sub: [[0, '正常'], [1, '关闭']],
    render: t => {
      let text = t;
      if (text === '' || text === '0') {
        text = (
          <Icon type="check-circle" theme="filled" style={{ color: 'limegreen', fontSize: 20 }} />
        );
      } else {
        text = (
          <Icon type="minus-circle" theme="filled" style={{ color: 'lightgray', fontSize: 20 }} />
        );
      }
      return text;
    },
  },
  {
    title: '注册日期',
    dataIndex: 'addTime',
    width: 120,
    render: text => <div style={{ color: 'darkgray' }}>{text.substr(0, 10)}</div>,
  },
];

class page extends Component {
  state = {
    pagination: {
      current: 1,
      pageSize,
      onShowSizeChange: (_, size) => {
        const { pagination } = this.state;
        pagination.pageSize = size;
      },
    },
    searchs: [],
    dialog_action: 'create',
    dialog_title: tools.funcDlgTitle(dlgTitle),
  };

  componentWillMount() {
    console.clear();
    reqApi = tools.funcGetApiName();
    const { props } = this;
    props[reqApi].selectOne = false;
    props[reqApi].noSelect = true;
    props[reqApi].dialog_visible = false;
    this.funcReadGrid();

    const payload = {
      userId: tools.funcGetUserId(),
      token: tools.funcGetToken(),
    };

    payload.currentPage = 1;
    payload.pageSize = 1000;
    props.dispatch({
      type: reqApi + '/role',
      payload,
    });
  }

  // 读取表记录
  funcReadGrid = (params = {}) => {
    const { props, state } = this;
    props[reqApi].loading = true;

    const payload = {
      userId: tools.funcGetUserId(),
      token: tools.funcGetToken(),
      currentPage: 1,
      pageSize: state.pagination.pageSize,
      searchs: [...state.searchs],
      ...params,
    };
    props.dispatch({
      type: reqApi + '/submit',
      payload,
    });
  };

  // 表格翻页
  funcOnChangePage = pagination => {
    const { state } = this;
    state.pagination.current = pagination.current;

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    this.funcReadGrid(params);
  };

  // 表格行选中事件
  funcSelect = rows => {
    const { props } = this;
    const selectedRowKeys = [];
    for (let i = 0; i < rows.length; i += 1) {
      const { id } = rows[i];
      selectedRowKeys.push(id);
    }

    props[reqApi].noSelect = rows.length === 0;
    props[reqApi].selectOne = rows.length === 1;
    props[reqApi].selectedRowKeys = selectedRowKeys;
    props[reqApi].gridSel_rows = rows;
    this.setState({});
  };

  // 新增
  funcCreate = () => {
    const { props } = this;
    props[reqApi].dialog_visible = true;
    this.setState({
      dialog_action: 'create',
      dialog_title: tools.funcDlgTitle(dlgTitle),
    });
    props.form.resetFields();
  };

  // 保存
  funcSave = () => {
    const { props, state } = this;
    props.form.validateFields((err, val) => {
      if (err) return err;

      const values = val;
      if (state.dialog_action === 'edit') {
        const ids = props[reqApi].selectedRowKeys;
        const lastId = ids[ids.length - 1];
        values.id = parseInt(lastId, 10);
        if (values.status !== undefined) values.status = values.status === true ? '0' : '1';
        if (changeValues.passwd) values.passwd = md5.md5(values.passwd);
      } else {
        values.passwd = md5.md5(values.passwd);
        values.remark = values.remark === undefined ? '' : values.remark;
        values.status = values.status === undefined ? true : values.status;
        values.status = values.status === true ? '0' : '1';
      }
      values.roles = JSON.stringify(values.roles);

      props[reqApi].dialog_loading = true;

      const payload = {
        userId: tools.funcGetUserId(),
        token: tools.funcGetToken(),
        action: state.dialog_action,
        model: values,
      };
      props.dispatch({
        type: reqApi + '/save',
        payload,
      });
      return true;
    });
  };

  // 新增对话框的取消按钮的点击事件
  funcDialogCancel = () => {
    const { props } = this;
    props[reqApi].dialog_visible = false;
    this.setState({});
  };

  // 删除
  funcDelete = () => {
    const { props } = this;
    let names = '';
    for (let i = 0; i < props[reqApi].gridSel_rows.length; i += 1) {
      names += props[reqApi].gridSel_rows[i].name;
      if (i + 1 < props[reqApi].gridSel_rows.length) names += ', ';
    }

    Modal.confirm({
      title: '删除?',
      content: (
        <div>
          你即将删除以下记录:
          <br />
          {names}
          <br />
          请确认是否删除?
        </div>
      ),
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk: () => {
        props[reqApi].loading = true;

        const payload = {
          userId: tools.funcGetUserId(),
          token: tools.funcGetToken(),
          ids: props[reqApi].selectedRowKeys.toString(),
        };
        props.dispatch({
          type: reqApi + '/dele',
          payload,
        });
      },
    });
  };

  // 编辑
  funcEdit = () => {
    const { props } = this;
    props[reqApi].dialog_visible = true;
    this.setState({
      dialog_action: 'edit',
      dialog_title: tools.funcDlgTitle(dlgTitle, 'edit'),
    });

    const row = { ...props[reqApi].gridSel_rows[0] };
    row.status = row.status === '0';
    const { id } = row;
    delete row.id;
    delete row.id_prikey;
    delete row.sequ;
    delete row.addTime;
    delete row.roleName;
    delete row.userLogo;

    props.form.setFieldsValue(row);
    changeValues = {};

    const payload = {
      userId: tools.funcGetUserId(),
      token: tools.funcGetToken(),
      action: 'edit',
      id,
    };
    props.dispatch({
      type: reqApi + '/echo',
      payload,
    }).then(() => {
      const { props } = this;
      const { echoModel } = props[reqApi];
      const { passwd, remark, roles } = echoModel;
      const newModel = {
        passwd,
        remark,
      };
      if (roles.length >= 3) {
        try {
          newModel.roles = JSON.parse(roles);
        } catch(error) {
          console.log('"echoModel.roles"不是一个json数组', error.toString());
        }
      }
      props.form.setFieldsValue(newModel);
      changeValues = {};
    });
  };

  // 记录查询表单提交
  funcOnSubmitSearch = arr => {
    const { state } = this;
    state.searchs = arr;
    state.pagination.current = 1;
    this.funcReadGrid();
  };

  render() {
    const { props, state } = this;
    const { getFieldDecorator } = props.form;

    const data = {
      list: props[reqApi].data,
      pagination: { ...state.pagination, total: props[reqApi].total },
    };

    const btn = props[reqApi].dialog_loading ? '保存' : tools.funcDlgBtnSave();

    return (
      <PageHeaderLayout title={pageTitle}>
        <Card bordered={false}>
          <SearchForm fields={fields} onSubmit={this.funcOnSubmitSearch} />
          <Button.Group>
            <Button icon="file-add" type="primary" onClick={this.funcCreate}>
              新增
            </Button>
            <Button icon="edit" onClick={this.funcEdit} disabled={!props[reqApi].selectOne}>
              编辑
            </Button>
            <Button
              icon="delete"
              type="danger"
              onClick={this.funcDelete}
              disabled={props[reqApi].noSelect}
            >
              删除
            </Button>
          </Button.Group>
          <br />
          <br />
          <StandardTable
            columns={fields}
            loading={props[reqApi].loading}
            data={data}
            onChange={this.funcOnChangePage}
            onSelectRow={this.funcSelect}
            selectedRows={props[reqApi].gridSel_rows}
          />
          <Modal
            width={modalWidth}
            title={state.dialog_title}
            visible={props[reqApi].dialog_visible}
            onOk={this.funcSave}
            onCancel={this.funcDialogCancel}
            bodyStyle={{ paddingBottom: 0 }}
            footer={[
              <Button key="cancel" onClick={this.funcDialogCancel}>
                {tools.funcDlgBtnCancel()}
              </Button>,
              <Button
                key="ok"
                type="primary"
                onClick={this.funcSave}
                loading={props[reqApi].dialog_loading}
              >
                {btn}
              </Button>,
            ]}
          >
            <Form>
              <Row gutter={{ md: 24, sm: 8 }}>
                <Col md={12} sm={24}>
                  <Form.Item label="用户名" {...formItemLayout2}>
                    {getFieldDecorator('userName', {
                      rules: [{ required: true, message: '请输入登录用户名' }],
                    })(<Input maxLength={20} autoFocus autoComplete="nope" />)}
                  </Form.Item>
                </Col>
                <Col md={12} sm={24}>
                  <Form.Item label="登录密码" {...formItemLayout2}>
                    {getFieldDecorator('passwd', {
                      rules: [{ required: true, message: '请输入登录密码' }],
                    })(<Input maxLength={20} type="password" autoComplete="new-password" />)}
                  </Form.Item>
                </Col>

                <Col md={12} sm={24}>
                  <Form.Item label="姓名" {...formItemLayout2}>
                    {getFieldDecorator('name', {
                      rules: [{ required: true, message: '请输入您的姓名' }],
                    })(<Input maxLength={10} />)}
                  </Form.Item>
                </Col>
                <Col md={12} sm={24}>
                  <Form.Item label="手机号码" {...formItemLayout2}>
                    {getFieldDecorator('phone', {
                      rules: [{ required: true, message: '请输入手机号码' }],
                    })(<Input type='number' min={13000000000} max={19999999999} />)}
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item label="用户角色" {...formItemLayout}>
                {getFieldDecorator('roles', {
                  rules: [{ required: true, message: '请选择用户角色' }],
                })(
                  <Select mode="tags" placeholder="请选择用户角色">
                    {props[reqApi].roleArr.map((item) => {
                      const { id, name } = item;
                      return (
                        <Select.Option key={id}>
                          {name}
                        </Select.Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
              <Form.Item label="用户状态" {...formItemLayout}>
                {getFieldDecorator('status', {
                  initialValue: true,
                  valuePropName: 'checked',
                })(
                  <Switch
                    checkedChildren={<Icon type="check" />}
                    unCheckedChildren={<Icon type="cross" />}
                  />
                )}
              </Form.Item>
              <Form.Item label="备注" {...formItemLayout}>
                {getFieldDecorator('remark')(
                  <Input.TextArea maxLength={255} autoSize={{ minRows: 5, maxRows: 10 }} />
                )}
              </Form.Item>
            </Form>
          </Modal>
        </Card>
      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create({
  onValuesChange: (props, value) => {
    changeValues = { ...changeValues, ...value };
  },
})(page);
export default connect(({ users }) => ({ users }))(page2);
